package com.yeziji.job.common;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.yeziji.job.business.jobInfo.base.JobInfo;
import com.yeziji.job.common.base.JobContextInfo;
import com.yeziji.utils.NanoIdUtils;

import java.util.Date;

/**
 * 任务上下文信息
 *
 * @author hwy
 * @since 2024/06/27 18:19
 **/
public class JobContext {
    /**
     * 当前执行的任务缓存
     */
    private static final Cache<String, JobContextInfo> CURRENT_RUNNABLE_CACHE = CacheBuilder.newBuilder()
            .initialCapacity(JobHolder.size())
            .maximumSize(5000)
            .build();

    /**
     * 当前线程执行的任务
     */
    private static final ThreadLocal<JobContextInfo> CURRENT_RUNNABLE = new ThreadLocal<>();

    /**
     * 绑定当前执行的任务
     *
     * @param contextInfo 任务信息
     */
    public static String bind(JobContextInfo contextInfo) {
        String flag = NanoIdUtils.randomNanoId();
        contextInfo.setFlag(flag);
        contextInfo.setExecuteTime(new Date());
        // set
        CURRENT_RUNNABLE.set(contextInfo);
        CURRENT_RUNNABLE_CACHE.put(flag, contextInfo);
        return flag;
    }

    /**
     * 更新任务信息
     *
     * @param flag        任务 flag
     * @param contextInfo 上下文信息
     */
    public static void update(String flag, JobContextInfo contextInfo) {
        CURRENT_RUNNABLE.set(contextInfo);
        CURRENT_RUNNABLE_CACHE.put(flag, contextInfo);
    }

    /**
     * 获取 flag 信息
     *
     * @param flag flag 标识
     * @return {@link JobInfo}
     */
    public static JobContextInfo get(String flag) {
        return CURRENT_RUNNABLE_CACHE.getIfPresent(flag);
    }

    /**
     * 获取当前信息
     *
     * @return {@link JobInfo}
     */
    public static JobContextInfo get() {
        return CURRENT_RUNNABLE.get();
    }

    /**
     * 解除对当前任务的绑定
     */
    public static void unbind(String flag) {
        if (flag != null) {
            CURRENT_RUNNABLE.remove();
            CURRENT_RUNNABLE_CACHE.invalidate(flag);
        }
    }
}